package com.ioffice.export.excel.engine.data.excel.impl.tree;

import java.util.List;

import com.ioffice.exception.IOfficeException;
import com.ioffice.export.excel.data.ExcelSheetDataInfo;
import com.ioffice.export.excel.engine.data.excel.impl.AbstractEngineDataSheetCompent;
import com.ioffice.export.excel.sheet.cell.SheetCell;
import com.ioffice.export.excel.sheet.tree.SheetCrossHeader;
import com.ioffice.export.excel.type.ExcelSheetTreeType;
import com.ioffice.export.excel.type.ExcelSheetType;

import static com.ioffice.export.excel.engine.data.excel.EngineDataSheetCell.getSheetCell;
import static com.ioffice.export.excel.engine.data.excel.EngineDataSheetCell.addChidrenSheetCell;



public class EngineDataSheetTreeCrossHeader extends AbstractEngineDataSheetCompent{

	private ExcelSheetDataInfo parentData;
	private SheetCell parentCell;
	private ExcelSheetDataInfo childData;
	
	private  int deepCount=0;
	private  int leafCount=0;
	private  int leafCounts=0;
	
	
	public EngineDataSheetTreeCrossHeader() {
		compent=new SheetCrossHeader();
	}
	
	@Override
	public void data2SheetCompent(List<ExcelSheetDataInfo> datas,ExcelSheetType sheetType) throws IOfficeException {
		ExcelSheetTreeType treeType=(ExcelSheetTreeType)sheetType;
		for(int i=0,size=datas.size();i<size;i++){
			parentData=datas.get(i);
			if(parentData.getChildLevel()==0){//得到root节点
				if(parentData.getParentId()==treeType.getCrossHeaderParentId()){//是否为交叉表头
					parentCell=getSheetCell(parentData);
					for(int j=i+1;j<datas.size();j++){
						childData=datas.get(j);
						if(parentData.getId()==childData.getParentId()){
							//是否为第一级节点并第一级节点的parentId为root节点的id
							if(childData.getChildLevel()==1){
								deepCount=1;
								parentCell=getAllChildrenCell(parentCell, childData.getParentId(), j, datas);
							}
						}
					}
					((SheetCrossHeader)compent).setDeepCount(deepCount);
					((SheetCrossHeader)compent).addChild(parentCell);
				}
			}
		}
	}

	
	public int getSheetCrossHeaderNodesLeaf(SheetCrossHeader cross){
		List<SheetCell> list=cross.getChild();
		leafCounts=0;
		for(SheetCell cell:list){
			getChildNodesLeaf(cell);
		}
		return leafCounts;
	}
	
	private void getChildNodesLeaf(SheetCell cell){
		int childCount =cell.getChildSize();
		List<SheetCell> list=cell.getChild();
		if(childCount==0)
			leafCounts++;
		else{
			for(SheetCell child:list){
				if(child!=null)
					getChildNodesLeaf(child);
			}
		}
	}
	
	
	private SheetCell getAllChildrenCell(SheetCell parentCell,int parentId,int stemp,List<ExcelSheetDataInfo> list){
		ExcelSheetDataInfo info=list.get(stemp);
		SheetCell cell=null;
		if(info.getParentId()==parentId){
			cell=getSheetCell(info);
			for(int i=stemp+1,size=list.size();i<size;i++){
				cell=getAllChildrenCell(cell, info.getId(), i, list);
			}
			deepCount++;
			leafCount++;
			addChidrenSheetCell(parentCell, cell);
		}
		return parentCell;
	}
}
